package game

import (
	"errors"
	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"higame/modules/utils"
	"strings"
)

func bindData(ctx *gin.Context) (*Schema, error) {
	gameSchema := New()
	err := ctx.ShouldBind(gameSchema)
	if err != nil {
		errText := err.Error()
		var msgList [] string
		if strings.Contains(errText, "'Name' failed on the 'required' tag") {
			msgList = append(msgList, "游戏名称不能为空")
		}
		if strings.Contains(errText, "'Code' failed on the 'required' tag") {
			msgList = append(msgList, "游戏编码不能为空")
		}
		if strings.Contains(errText, "'Version' failed on the 'required' tag") {
			msgList = append(msgList, "游戏版本不能为空")
		}
		if strings.Contains(errText, "'DownUrl' failed on the 'required' tag") {
			msgList = append(msgList, "下载网址不能为空")
		}
		if strings.Contains(errText, "'IsUp' failed on the 'required' tag") {
			msgList = append(msgList, "是否更新不能为空")
		}
		if strings.Contains(errText, "'Icon' failed on the 'required' tag") {
			msgList = append(msgList, "游戏图标不能为空")
		}
		if strings.Contains(errText, "'HomePage' failed on the 'required' tag") {
			msgList = append(msgList, "游戏主页不能为空")
		}
		if strings.Contains(errText, "'AppName' failed on the 'required' tag") {
			msgList = append(msgList, "执行文件名称不能为空")
		}
		if len(msgList) > 0 {
			return nil, errors.New(strings.Join(msgList, "，") + "。")
		}
	}
	gameSchema.AddTime = utils.Timestamp()
	return gameSchema, nil
}

func bindID(ctx *gin.Context) (*Schema, error) {
	gameSchema := New()
	_id := ctx.PostForm("_id")
	objID, err := primitive.ObjectIDFromHex(_id)
	if err != nil {
		return nil, errors.New("_id出错")
	}
	gameSchema.ID = objID
	return gameSchema, nil
}
